﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FZKJ.COMMON;
using Newtonsoft.Json;
using FZKJ.ZHXJ.Models;
using System.Transactions;

namespace FZKJ.ZHXJ.Controllers
{
    public class BaseInfoController : Controller
    {
        //
        // GET: /BaseInfo/
        /// <summary>
        /// 车辆新管理
        /// </summary>
        /// <returns></returns>
        public ActionResult CarManagement()
        {
            return View();
        }

        /// <summary>
        /// 获取所有汽车
        /// </summary>
        /// <returns></returns>
        public string GetCards()
        {
            var data = new ResultInfo<List<object>>();
            var pageSize = int.Parse(Request.Params["pagesize"]);
            var pageNo = int.Parse(Request.Params["pageno"]);
            var order = Request.Params["order"];
            //查询条件组织
            var where = " (isdel is null or isdel=0) AND ";// string.Empty;
            if (!string.IsNullOrWhiteSpace(Request.Params["query"]))
            {
                string query = Request.Params["query"];
                where += $" (carowner like'%{query}%' or licenseplate like '%{query}%' or enginenumber like '%{query}%') AND ";
            }
            if (!string.IsNullOrWhiteSpace(Request.Params["startTime"]))
            {
                where += $" inputtime>='{Request.Params["startTime"]}' AND ";
            }
            if (!string.IsNullOrWhiteSpace(Request.Params["endTime"]))
            {
                where += $" inputtime<='{Request.Params["endTime"]}' AND ";
            }

            LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
            if (li.RoleCode != "1001")
            {
                var users = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'");
                var user = users.Count > 0 ? users[0] : new Model.base_userinfo();

                where += " inputor='" + user.id + "' AND ";
            }
            if (!string.IsNullOrEmpty(where))
                where = where.Substring(0, where.Length - 4);
            var startIndex = pageSize * (pageNo - 1) + 1;
            var endIndex = pageSize * pageNo;
            var dt = new BLL.buss_vehicle().GetListByPage(where, order, startIndex, endIndex).Tables[0];
            data.IsSucceed = true;
            data.TotalCount = new BLL.buss_vehicle().GetListByPage(where, order, -1, -1).Tables[0].Rows.Count;
            data.Entity = JsonHelper.DataTableToList(dt);
            return JsonConvert.SerializeObject(data);
        }

        [HttpPost]
        public string SaveCar(string json)
        {

            ResultInfo result = new ResultInfo(false);
            try
            {
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var model = JsonConvert.DeserializeObject<Model.buss_vehicle>(json);
                var users = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'");
                var user = users.Count > 0 ? users[0] : new Model.base_userinfo();
                if (model.id == "-1")
                {
                    model.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    model.inputor = user.id.ToString();
                    model.inputtime = DateTime.Now;
                    if (user.rolecode != "1001")
                    {
                        model.state = 0;
                    }
                    else
                    {
                        model.state = 1;
                    }
                    new BLL.buss_vehicle().Add(model);
                    result.IsSucceed = true;
                    result.Message = "添加成功";
                }
                else
                {
                    var m = new BLL.buss_vehicle().GetModel(model.id);
                    m.vehiclecode = model.vehiclecode;
                    m.carowner = model.carowner;
                    m.carmodel = model.carmodel;
                    m.licenseplate = model.licenseplate;
                    m.drivingnumber = model.drivingnumber;
                    m.enginenumber = model.enginenumber;
                    m.pedestal = model.pedestal;
                    m.mobile = model.mobile;
                    m.transportcompany = model.transportcompany;
                    m.nuclearweight = model.nuclearweight;
                    m.initialdate = model.initialdate;
                    m.businessattribution = model.businessattribution;
                    m.businessdepartment = model.businessdepartment;
                    m.businessowner = model.businessowner;
                    m.option1 = model.option1;
                    m.option2 = model.option2;
                    m.option3 = model.option3;
                    m.updateor = user.id.ToString();
                    m.updatetime = DateTime.Now;
                    if (user.rolecode != "1001")
                    {
                        m.state = 0;
                    }
                    else
                    {
                        m.state = 1;
                    }
                    new BLL.buss_vehicle().Update(m);
                    result.IsSucceed = true;
                    result.Message = "添加成功";

                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "添加失败";
            }

            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string DeleteCar(string ids)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                foreach (var item in ids.Split(','))
                {
                    var model = new BLL.buss_vehicle().GetModel(item);
                    model.isdel = 1;
                    model.deltime = DateTime.Now;
                    new BLL.buss_vehicle().Update(model);
                }
                result.IsSucceed = true;
                result.Message = "删除成功";
            }
            catch (Exception e)
            {
                result.IsSucceed = false;
                result.Message = "删除失败";
            }
            return JsonConvert.SerializeObject(result);
        }


        public ActionResult Policy()
        {
            return View();
        }

        public string GetPolicies()
        {
            var data = new ResultInfo<List<object>>();
            var pageSize = int.Parse(Request.Params["pagesize"]);
            var pageNo = int.Parse(Request.Params["pageno"]);
            var order = Request.Params["order"];
            //查询条件组织

            var where = "(isdel is null or isdel=0) AND ";
            if (!string.IsNullOrWhiteSpace(Request.Params["query"]))
            {
                string query = Request.Params["query"];
                where += $" (company like'%{query}%' or policynumber like '%{query}%' or insuran like '%{query}%' or insurancard like'%{query}%' or policyagent like '%{query}%') AND ";
            }
            //if (!string.IsNullOrWhiteSpace(Request.Params["startTime"]))
            //{
            //    where += $" inputtime>='{Request.Params["startTime"]}' AND ";
            //}
            //if (!string.IsNullOrWhiteSpace(Request.Params["startTime"]))
            //{
            //    where += $" inputtime<='{Request.Params["endTime"]}' AND ";
            //}

            if (!string.IsNullOrEmpty(where))
                where = where.Substring(0, where.Length - 4);
            var startIndex = pageSize * (pageNo - 1) + 1;
            var endIndex = pageSize * pageNo;
            var dt = new BLL.buss_policy().GetListByPage(where, order, startIndex, endIndex).Tables[0];
            data.IsSucceed = true;
            data.TotalCount = new BLL.buss_policy().GetListByPage(where, order, -1, -1).Tables[0].Rows.Count;
            data.Entity = JsonHelper.DataTableToList(dt);
            return JsonConvert.SerializeObject(data);
        }


        [HttpPost]
        public string SavePloicy(string json)
        {

            ResultInfo result = new ResultInfo(false);
            try
            {
                LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                var model = JsonConvert.DeserializeObject<Model.buss_policy>(json);
                var info = JsonConvert.DeserializeObject<Model.buss_baseinfo>(json);
                if (model.id == "-1")
                {
                    model.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    string id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    var baseinfo = new Model.buss_baseinfo()
                    {
                        inputor = li.UserName,
                        id = id
                    };
                    model.baseinfoId = id;
                    new BLL.buss_policy().Add(model);
                    new BLL.buss_baseinfo().Add(baseinfo);
                    result.IsSucceed = true;
                    result.Message = "添加成功";
                }
                else
                {
                    var m = new BLL.buss_policy().GetModel(model.id);
                    var baseinfo = new BLL.buss_baseinfo().GetModel(m.baseinfoId);
                    m.company = model.company;
                    m.policynumber = model.policynumber;
                    m.insuran = model.insuran;
                    m.insurancard = model.insurancard;
                    m.policyagent = model.policyagent;
                    baseinfo.businessattribution = info.businessattribution;
                    baseinfo.businessdepartment = info.businessdepartment;
                    baseinfo.businessowner = info.businessowner;
                    baseinfo.option1 = info.option1;
                    baseinfo.option2 = info.option2;
                    baseinfo.option3 = info.option3;
                    baseinfo.updateor = li.UserName;
                    baseinfo.updatetime = DateTime.Now;
                    new BLL.buss_policy().Update(m);
                    new BLL.buss_baseinfo().Update(baseinfo);
                    result.IsSucceed = true;
                    result.Message = "添加成功";

                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "添加失败";
            }

            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string DeletePloicies(string ids)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                foreach (var item in ids.Split(','))
                {
                    var model = new BLL.buss_policy().GetModel(item);
                    var baseinfo = new BLL.buss_baseinfo().GetModel(model.baseinfoId);
                    baseinfo.isdel = 1;
                    baseinfo.deltime = DateTime.Now;
                    new BLL.buss_baseinfo().Update(baseinfo);
                }
                result.IsSucceed = true;
                result.Message = "删除成功";
            }
            catch (Exception e)
            {
                result.IsSucceed = false;
                result.Message = "删除失败";
            }
            return JsonConvert.SerializeObject(result);
        }

        public ActionResult RoleCode()
        {
            return View();
        }
        /// <summary>
        /// 获取单个规则码表信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string OneRoleCode(string id)
        {
            ResultInfo<List<object>> result = new ResultInfo<List<object>>();
            var bll = new FZKJ.BLL.buss_attribution();
            var dt = bll.GetList("id='" + id + "'").Tables[0];
            result.IsSucceed = true;
            result.Message = "获取成功！";
            result.Entity = JsonHelper.DataTableToList(dt);
            List<object> mb_list = new List<object>();
            result.Extend = mb_list;
            return JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 删除码表数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string RoleCodeDelete(int id)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                var bll = new BLL.buss_attribution();
                var model = bll.GetModel(id);
                model.isdel = "1";
                if (bll.Update(model))
                {
                    result.IsSucceed = true;
                    result.Message = "保存成功！";
                    PublicClass.AddLog("操作", "修改码表数据" + model.value + "！");
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "保存失败！";
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = "保存失败！";
            }
            return JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 码表添加/修改保存
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public string RoleCodeSave(string json)
        {
            ResultInfo result = new ResultInfo(false);
            LoginInfo userInfo = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
            var bll = new FZKJ.BLL.buss_attribution();
            var model = JsonConvert.DeserializeObject<Model.buss_attribution>(json);
            //新增
            if (model.id == -1)
            {
                model.isdel = "0";
                if (bll.Add(model) > 0)
                {
                    result.IsSucceed = true;
                    result.Message = "保存成功！";
                    PublicClass.AddLog("操作", "新增码表数据" + model.value + "！");
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "保存失败！";
                }
            }
            //修改
            else
            {
                model.isdel = "0";
                if (bll.Update(model))
                {
                    result.IsSucceed = true;
                    result.Message = "保存成功！";
                    PublicClass.AddLog("操作", "修改码表数据" + model.value + "！");
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "保存失败！";
                }
            }
            return JsonConvert.SerializeObject(result);
        }

        public string PassOrNoPass(string ids, int state)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                string where = "";
                foreach (var item in ids.Split(','))
                {
                    where += "'" + item + "',";
                }
                if (where.Length > 0)
                {
                    where = where.Remove(where.Length - 1);
                    new BLL.buss_vehicle().Update(where, state);
                    result.IsSucceed = true;
                    result.Message = "操作成功";
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = "操作失败";
            }
            return JsonConvert.SerializeObject(result);

        }

        public string ImportPolicy()
        {
            ResultInfo result = new ResultInfo(false);
            string errorData = "";
            try
            {
                List<Model.buss_policy> list = new List<Model.buss_policy>();
                var file = Request.Files[0];
                string extends = file.FileName.Split('.')[1];
                if (extends != "xlsx" && extends != "xls")
                {
                    result.IsSucceed = false;
                    result.Message = "请上传正确格式的excel表格！";
                }
                else
                {

                    var reflist = FileToEntity.FileToEntityFunc<Model.buss_policy>(HttpContext, "保单数据", "policy.json", file);
                    LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                    var currentMember = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'");
                    string str = "";
                    bool isExist = false;
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                    {
                        foreach (var item in reflist)
                        {
                            item.id = Guid.NewGuid().ToString();
                            var model = new BLL.sys_dict().GetModelList(" label='" + item.company + "'");
                            if (model.Count == 0)
                            {
                                str = "保险公司" + item.company + "在数据库中未找到";
                                isExist = true;
                                break;
                            }
                            var baseinfo = new Model.buss_baseinfo()
                            {
                                inputor = currentMember[0].id.ToString(),
                                id = Guid.NewGuid().ToString()
                            };
                            item.baseinfoId = baseinfo.id;
                            item.company = model[0].id.ToString();
                            new BLL.buss_baseinfo().Add(baseinfo);
                            new BLL.buss_policy().Add(item);
                        }
                        if (!isExist)
                        {
                            scope.Complete();
                            result.IsSucceed = true;
                            result.Message = "导入成功";
                        }
                        else
                        {
                            result.IsSucceed = false;
                            result.Message = str;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(result);
        }

        public string ImportCar()
        {
            ResultInfo result = new ResultInfo(false);
            string errorData = "";
            try
            {
                List<Model.buss_vehicle> list = new List<Model.buss_vehicle>();
                var file = Request.Files[0];
                string extends = file.FileName.Split('.')[1];
                if (extends != "xlsx" && extends != "xls")
                {
                    result.IsSucceed = false;
                    result.Message = "请上传正确格式的excel表格！";
                }
                else
                {

                    var reflist = FileToEntity.FileToEntityFunc<Model.buss_vehicle>(HttpContext, "营运车辆", "vehicle.json", file);
                    LoginInfo li = SessionHelper.ReadSession<LoginInfo>(SessionKeys.LoginInfoKey);
                    var currentMember = new BLL.base_userinfo().GetModelList(" username='" + li.UserName + "'");
                    bool isAllExist = true;
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                    {
                        foreach (var item in reflist)
                        {
                            var isExist = new BLL.sys_dict().GetModelList($" label='" + item.carmodel + "'");
                            if (isExist.Count == 0)
                            {
                                result.IsSucceed = false;
                                result.Message = "车型为" + item.carmodel + "未找到！";
                                isAllExist = false;
                                break;
                            }
                            item.id = Guid.NewGuid().ToString();
                            item.inputor = currentMember[0].id.ToString();
                            item.inputtime = DateTime.Now;
                            item.state = 0;
                            item.activityState = 0;
                            new BLL.buss_vehicle().Add(item);
                        }
                        if (isAllExist)
                        {
                            scope.Complete();
                            result.IsSucceed = true;
                            result.Message = "导入成功";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(result);
        }
    }
}
